package com.liwenfeng.proxy;

import java.lang.reflect.Proxy;
import java.util.Arrays;
/*
* 创建代理对象
* */
public class ProxyUtil {

    public static UserService createProxy(UserService userService) {
        return (UserService) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                new Class[]{UserService.class},
                (proxy, method, args) -> {
                    Object rs;
                    if (method.getName().equals("deleteUsers") || method.getName().equals("selectUsers")) {

                        long start = System.currentTimeMillis();
                        rs = method.invoke(userService, args);
                        long end = System.currentTimeMillis();
                        System.out.println(method.getName() + " 方法耗时：" + (end - start));
                    } else {
                        rs = method.invoke(userService, args);
                    }
                    return rs;
                });
    }

    public static void main(String[] args) {
        UserService userServiceProxy = createProxy(new UserServiceImpl());
        userServiceProxy.deleteUsers();
        String[] strings = userServiceProxy.selectUsers();
        System.out.println(Arrays.toString(strings));

    }

}
